export default defineNuxtRouteMiddleware((to, from) => {
  const toPath = to.path;
  const isAuth = toPath.startsWith("/auth");
  const isHomePage = toPath === "/";
  const isAdmin = toPath.startsWith("/admin");
  const isUser = toPath.startsWith("/user");
  const isShortUrl =
    /^\/[a-zA-Z0-9]{5,6}$/.test(toPath) && !isAdmin && !isUser && !isAuth;

  if (!(isAuth || isHomePage || isShortUrl)) {
    const { auth } = isAdmin ? useAdminAuth() : useAuth();
    const loginPage = `/auth/${isAdmin ? "admin" : "user"}-login`;

    if (!auth.value) {
      const fromPath = from.path;
      const target = fromPath.endsWith("/logout")
        ? isAdmin
          ? "/admin"
          : "/user"
        : fromPath;
      return navigateTo({ path: loginPage, query: { to: target } });
    }
  }
});
